package com.jl.encrypt.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;

/**
 * res对称加密
 */
public class JLAES {

    /**
     * 获取密钥
     *
     * @return
     */
    public static String getKey() {
        byte[] encoded = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
        return Base64.encode(encoded);
    }

    /**
     * 加密
     *
     * @param str
     * @param key
     * @return
     */
    public static String encode(String str, String key) {
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, Base64.decode(key));
        byte[] encrypt = aes.encrypt(str);
        return Base64.encode(encrypt);
    }

    /**
     * 解密
     *
     * @param str
     * @param key
     * @return
     */
    public static String decode(String str, String key) {
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, Base64.decode(key));
        String decryptStr = aes.decryptStr(Base64.decode(str), CharsetUtil.CHARSET_UTF_8);
        return decryptStr;
    }

}
